package com.xyxy.platform.modules.core.web.filter;

import com.xyxy.platform.modules.core.Constants;
import com.xyxy.platform.modules.core.utils.DateUtil;
import com.xyxy.platform.modules.core.web.WebConstant;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

/**
 * 多文件合并 过滤器
 *
 * @author caizhengda
 * @version [版本号, 2016-04-25]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public class MergeFilter extends OncePerRequestFilter {

    protected static final Logger logger = LoggerFactory.getLogger(MergeFilter.class);

    /**
     * 登录用户 session过滤, js,css 文件合并
     *
     * @param request
     * @param response
     * @param chain
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        // add by fang_wu 2013-06-27 begin
        // IE下 iframe不允许创建cookie,需要服务端支持P3P协议
        response.setHeader("P3P", "CP=\"CAO PSA OUR\"");
        // add by fang_wu 2013-06-27 end

        PrintWriter pw;

        String reqUri = request.getRequestURI();
        String contentPath = request.getSession().getServletContext().getContextPath();

        boolean isJs = reqUri.startsWith(request.getContextPath() + "/static/js");
        boolean isCss = reqUri.startsWith(request.getContextPath() + "/static/css");
        if (isJs || isCss) {
            if (!logger.isDebugEnabled()) {
                // 设置浏览器重定向
                Long ifModifiedSince = request.getDateHeader("If-Modified-Since");
                Long lastModified = WebConstant.LAST_MODIFIED.get("lastModified");
                logger.debug("{}: {}, {}: {}", new Date(ifModifiedSince), ifModifiedSince, new Date(lastModified), lastModified);
                response.setDateHeader("Last-Modified", lastModified);
                response.setDateHeader("Expires", System.currentTimeMillis() + 1314000000);
                if (null != ifModifiedSince && ifModifiedSince != -1
                        && DateUtil.format(new Date(lastModified)).equals(DateUtil.format(new Date(ifModifiedSince)))) {
                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
                    response.getOutputStream().close();
                    return;
                }
            }

            String rootPath = request.getSession().getServletContext().getRealPath("/");
            // js文件合并，请求类似于?lib/seajs/2.2.3/sea.min.js,lib/seajs/2.2.3/seajs-combo.min.js
            if (request.getParameterNames().hasMoreElements()) {
                Object elem = request.getParameterNames().nextElement();
                if (elem != null) {
                    pw = response.getWriter();

                    if (isJs) {
                        response.setHeader("Content-Type", "text/javascript;charset=UTF-8");
                    } else {
                        response.setHeader("Content-Type", "text/css;charset=UTF-8");
                    }

                    String param = elem.toString();
                    param = param.substring(1, param.length());
                    String fileBasePath = reqUri.substring(contentPath.length());
                    String[] paths = param.split(",");
                    for (String filePath : paths) {
                        if (filePath.lastIndexOf("@") != -1) {
                            filePath = filePath.substring(0, filePath.indexOf("@"));
                        }
                        File file = new File(rootPath + fileBasePath + filePath);
                        if (file.exists()) {
                            InputStream is = new FileInputStream(file);
                            IOUtils.copy(is, pw, Constants.ENCODING);
                            pw.flush();
                        }
                    }
                    pw.close();
                    return;
                }
            } else
            // 单个js或者css
            {
                String reqUrl = request.getRequestURI();
                if (reqUrl.lastIndexOf("@") != -1) {
                    reqUrl = reqUrl.substring(0, reqUrl.lastIndexOf("@"));
                }
                //reqUrl = reqUrl.replace("\\", "/");

                if (reqUrl.endsWith(".js") || reqUrl.endsWith(".css")) {
                    pw = response.getWriter();
                    if (reqUrl.endsWith(".js")) {
                        response.setHeader("Content-Type", "text/javascript;charset=UTF-8");
                    } else {
                        response.setHeader("Content-Type", "text/css;charset=UTF-8");
                    }
                    File file = new File(rootPath + reqUrl.substring(request.getContextPath().length()));
                    if (file.exists()) {
                        InputStream is = new FileInputStream(file);
                        IOUtils.copy(is, pw, Constants.ENCODING);
                        pw.flush();
                    } else {
                        response.setStatus(HttpServletResponse.SC_ACCEPTED);
                    }
                    pw.close();

                } else {
                    chain.doFilter(request, response);
                }
                return;
            }
        }

    }
}
